<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
// to-do: sales -> juris -> distributor selection
function invoice_add_page($id) {
    return drupal_get_form('invoice_edit_form',$id);
}

function invoice_edit_page($id) {
    return drupal_get_form('invoice_edit_form', $id);
}

function invoice_edit_form($form, &$form_state) {
    global $user;
    if (!empty($_GET['distributor_id'])) {
        $form_state['distributor_id'] = $_GET['distributor_id'];
    }
    if(empty( $form_state['distributor_id'])) {}else{
        $form['#distributor_id'] = $form_state['distributor_id'];
        $res = get_info($form['#distributor_id'],'distributor');
        $form['#distributor_name'] = $res[0]->distributor_name;
//        $addr_red = get_all_addrname($res[0]->addr_id);
//        $province = $addr_red[0]->province?$addr_red[0]->province:"";
//        $city = $addr_red[0]->city? '  '.$addr_red[0]->city:"";
//        $county = $addr_red[0]->county? '  '.$addr_red[0]->county:"";
//        $town = $addr_red[0]->town? '  '.$addr_red[0]->town:"";
//        $village = $addr_red[0]->village? '  '.$addr_red[0]->village:"";
//        $form['#farmer_addr'] =$province.$city.$county.$town.$village;
    }
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('invoice', 'id', $id);
        if (empty($record)) {
            drupal_set_message(t('销售发票不存在！'), 'status', FALSE);
            return $form;
        }
        $form_state['id'] = $id;
    }
// 判断用户角色
    if(!nonghua_user_access('invoice', 'view', $id, !empty($record) ? $record->author_uid:0,!empty($record) ? $record->distributor_id:0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    if(!empty($_GET['distributor_id'])){
        $record->distributor_id = $_GET['distributor_id'];
    }
    $form['distributor_name'] = _insert_distributor_select_info($form,$form_state,$record->distributor_id);
    $form['invoice_id'] = array(
        '#type' => 'textfield',
        '#title' => '发票编号',
        '#size' => 32,
        '#maxlength' => 10,
        '#default_value' => !empty($record) ? $record->invoice_id : '',
        '#required' => TRUE,
    );

    $form['invoice_date'] = array(
        '#title' => '开票日期',
        '#type' => 'metercomm_date',
        '#default_value' =>  _date_db_2_form(!empty($record) ? $record->invoice_date : ''),
        '#required' => TRUE,
    );

    $form['employee_list']   =  _insert_loginuser_choose_salesman_selection($user,!empty($record)?$record->salesman_id:$user->uid,NULL,'add');
//    $form['distributor'] = _insert_login_salesman_distributor_selection_form($form,$form_state,$user->uid,!empty($record) ? $record->distributor_id:'');
    $form['distributor_name'] = _insert_distributor_select_info($form,$form_state,$record->distributor_id);
    $types = db_select('sales_type', 'E')
        -> fields('E',array('sales_type_id', 'sales_type_name'))
        -> execute();
    foreach ($types as $sales_type) {
        $sales_type_options[$sales_type->sales_type_id] = $sales_type->sales_type_name;
    }
    $form['sales_type'] = array(
        '#title' => '销售类型',
        '#type' => 'select',
        '#options' => $sales_type_options,
        '#default_value' => !empty($record) ? $record->sales_type_id : '',
        '#required' => TRUE,
    );

   $form['sacfvariety'] =  _insert_sacfvariety_selection_form(!empty($record) ? $record->sacfvariety_id : '','选择撒可富化肥品种'); //todo

    $form['quantity'] = array(
        '#type' => 'textfield',
        '#title' => '数量',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->quantity:'',
    );
//    _insert_address_selection_form($form, $form_state, 5, FALSE, !empty($record) ? $record->delivery_addr_id:'');
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->delivery_addr_id:'');
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, TRUE,  !empty($record) ? $record->delivery_addr_id:'','到站地址');


    $form['station'] = array(
        '#type' => 'textfield',
        '#title' => '到站地名',
        '#size' => 32,
        '#maxlength' => 10,
        '#default_value' => !empty($record) ? $record->station_name:'',
    );

    $form['railway'] = array(
        '#type' => 'textfield',
        '#title' => '路局',
        '#size' => 32,
        '#maxlength' => 10,
        '#default_value' => !empty($record) ? $record->railway_bureau:'',
    );

    $inout_options = array('关内' => '关内', '关外' => '关外');
    $form['inorout'] = array(
        '#type' => 'radios',
        '#title' => '关内/关外',
        '#default_value' => !empty($record) ? $record->inorout:'关内',
        '#options' => $inout_options,
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(2) !='add' ? '修改' : '添加',
        '#access' => nonghua_user_access('invoice', 'edit', $id, !empty($record) ? $record->author_uid:0,!empty($record) ? $record->distributor_id:0) ,
    );
    return $form;
}

function invoice_edit_form_validate($form, &$form_state) {
    $empty = false;
    $empty = !_address_element_validate($form_state);
    if(empty($form_state['values']['invoice_date'])){
        form_set_error('invoice_date', '必须填写 日期');
        $empty = true;
    }
    if(empty($form_state['values']['invoice_id'])){
        form_set_error('invoice_id','必须填写 发票号');
        $empty = true;
    }
    if(empty($form_state['values']['distributor_name'])){
        form_set_error('distributor','必须填写 经销商');
        $empty = true;
    }
    if(empty($form_state['values']['sales_type'])){
        form_set_error('sales_type','必须填写 销售类型');
        $empty = true;
    }
    if(empty($form_state['values']['sacfvariety'])){
        form_set_error('sacfvariety','必须填写 化肥品种');
        $empty = true;
    }
    if(!empty($form_state['values']['quantity'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['quantity']) || (strlen(explode('.',$form_state['values']['quantity'])[0])>8)) {
            form_set_error('quantity', "数量格式错误");
        }
    }
    if(!$empty && arg(2) === "add"){
        $query = db_select('invoice', 's');
        $query->condition('s.invoice_id',$form_state['values']['invoice_id']);
        $query->fields('s');
        $record = $query->execute()->fetchAssoc();
        if(!empty($record)){
            form_set_error('',"该发票号已存在" );
        }
    }
    if(!$empty && arg(2) === "edit") {
        $query = db_select('invoice', 's');
        $query->condition('s.invoice_id',$form_state['values']['invoice_id']);
        $query->condition('s.id', $form_state['id'], '!=');
        $query->fields('s');
        $record = $query->execute()->fetchAssoc();
        if(!empty($record)){
            form_set_error('',"该发票号已存在" );
        }
    }
    if(!empty($form_state['values']['distributor_name'])){
        $distributor_id = get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false);
        if(empty($distributor_id)){
            form_set_error('distributor_name', "经销商信息不存在！");
        }
    }
}

function invoice_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    if (arg(2) =='add') { //add new invoice
        $nid = db_insert('invoice') // Table name no longer needs {}
        ->fields(array(
            'invoice_id' => $form_state['values']['invoice_id'],
            'invoice_date' => _date_form_2_db($form_state['values']['invoice_date']),
            'salesman_id' => $form_state['values']['employee_list'],
            'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
            'sales_type_id' => $form_state['values']['sales_type'],
            'sacfvariety_id' => $form_state['values']['sacfvariety'],
            'quantity' => $form_state['values']['quantity'],
            'delivery_addr_id' => $address,
            'station_name' => $form_state['values']['station'],
            'railway_bureau' => $form_state['values']['railway'],
            'inorout' => $form_state['values']['inorout'],
            'author_uid' =>$user->uid,
            'timestamp' => time(),))
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
        }
        if(!empty($_GET['distributor_id'])){
            drupal_goto('sales/invoice/list',array('query' => array('distributor_id' => $_GET['distributor_id'])));
        }
       drupal_goto('sales/invoice/add/'.$nid);
    } else {
        $nid = db_update('invoice') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'invoice_id' => $form_state['values']['invoice_id'],
            'invoice_date' => _date_form_2_db($form_state['values']['invoice_date']),
            'salesman_id' => $form_state['values']['employee_list'],
            'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
            'sales_type_id' => $form_state['values']['sales_type'],
            'sacfvariety_id' => $form_state['values']['sacfvariety'],
            'quantity' => $form_state['values']['quantity'],
            'delivery_addr_id' => $address,
            'station_name' => $form_state['values']['station'],
            'railway_bureau' => $form_state['values']['railway'],
            'inorout' => $form_state['values']['inorout'],
//            'author_uid' => $user->uid,
            'timestamp' => time(),))
            -> condition('id',$id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
        if(!empty($_GET['distributor_id'])){
            drupal_goto('sales/invoice/list',array('query' => array('distributor_id' => $_GET['distributor_id'])));
        }
//        drupal_goto('sales/invoice/list');
    }
}